package com.jsh.erp.filter;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class TenantSqlFilter implements Interceptor, TenantLineHandler {

    private static final List<String> IGNORE_METHODS = Arrays.asList(
            "com.jsh.erp.datasource.mappers.UserMapperEx.getUserByWeixinOpenId",
            "com.jsh.erp.datasource.mappers.UserMapperEx.updateUserWithWeixinOpenId",
            "com.jsh.erp.datasource.mappers.UserMapperEx.getUserListByUserNameOrLoginName",
            "com.jsh.erp.datasource.mappers.UserMapperEx.disableUserByLimit",
            "com.jsh.erp.datasource.mappers.RoleMapperEx.getRoleWithoutTenant",
            "com.jsh.erp.datasource.mappers.LogMapperEx.insertLogWithUserId",
            "com.jsh.erp.datasource.mappers.UserBusinessMapperEx.getBasicDataByKeyIdAndType"
    );

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];

        if (IGNORE_METHODS.contains(ms.getId())) {
            return invocation.proceed();
        }

        // 其他方法会经过TenantLineInnerInterceptor处理
        return invocation.proceed();
    }

    @Override
    public Expression getTenantId() {
        // 返回null表示不添加租户条件
        return new NullValue();
    }

    @Override
    public String getTenantIdColumn() {
        return null;
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return true;
    }
}